package com.xidian.zhiancloud.service.dangerWorkTicket.WorkTicket;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xidian.zhiancloud.dao.syset.SysPositionMapper;
import com.xidian.zhiancloud.dao.syset.SysUserMapper;
import com.xidian.zhiancloud.dao.syset.usermanage.OrganizationMapper;
import com.xidian.zhiancloud.dao.workTicket.WorkTicketMapper;
import com.xidian.zhiancloud.dao.workTicket.WorkTicketTemplateMapper;
import com.xidian.zhiancloud.enums.GeneralResponseEnums;
import com.xidian.zhiancloud.exception.CustomizeException;
import com.xidian.zhiancloud.model.syset.Organization;
import com.xidian.zhiancloud.model.syset.SysPosition;
import com.xidian.zhiancloud.model.syset.SysUser;
import com.xidian.zhiancloud.model.dangerWorkTicket.WorkTicket;
import com.xidian.zhiancloud.model.dangerWorkTicket.WorkTicketTemplate;
import com.xidian.zhiancloud.qo.dangerWorkTicket.WorkTicketQO;
import com.xidian.zhiancloud.service.dangerWorkTicket.WorkApprove.UnsafeWorkApproveService;
import com.xidian.zhiancloud.vo.dangerWorkTicket.WorkTicketDTOVO;
import com.xidian.zhiancloud.vo.dangerWorkTicket.WorkTicketVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class WorkTicketService extends ServiceImpl<WorkTicketMapper, WorkTicket> implements IService<WorkTicket> {
    @Autowired
    private WorkTicketMapper workTicketMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysPositionMapper sysPositionMapper;

    @Autowired
    private WorkTicketTemplateMapper workTicketTemplateMapper;

    @Autowired
    private OrganizationMapper organizationMapper;

    @Autowired
    private WorkTicketTemplateService workTicketTemplateService;

    @Autowired
    private UnsafeWorkApproveService unsafeWorkApproveService;

    public WorkTicketDTOVO getVOById(Long id) {
        WorkTicketDTOVO workTicketDTOVO = new WorkTicketDTOVO();
        // 作业票基本内容
        WorkTicket workTicket = workTicketMapper.selectById(id);
        if (workTicket == null) {
            throw new CustomizeException(GeneralResponseEnums.GET_FAILED);
        }

        WorkTicketVO vo = new WorkTicketVO();
        BeanUtils.copyProperties(workTicket, vo);

        SysUser creator = sysUserMapper.selectById(vo.getCreatorId());                      // 作业创建人
        vo.setCreatorName(creator == null ? "该用户不存在" : creator.getName());

        SysUser principal = sysUserMapper.selectById(vo.getPrincipalId());                     // 监护人
        vo.setPrincipalName(principal == null ? "该用户不存在" : creator.getName());

        SysUser guardian = sysUserMapper.selectById(vo.getGuardianId());                      // 作业负责人
        vo.setGuardianName(guardian == null ? "该用户不存在" : creator.getName());

        SysPosition position = sysPositionMapper.selectById(vo.getPositionId());            // 作业地点
        vo.setLocationName(position == null ? "该位置不存在" : position.getName());

        String template = workTicketTemplateMapper.selectById(vo.getTicketType()).getName();    // 作业票名称
        vo.setWorkTemplateName(template == null ? "该作业票不存在" : template);

        Organization organization = organizationMapper.selectById(vo.getApplicantUnitId());
        vo.setApplicantUnitName(organization == null ? "该部门不存在" : organization.getName());

        String ids_s = vo.getWorkerIds();                                                   // 现场作业人员
        long[] ids_l = Arrays.stream(ids_s.split(",")).mapToLong(Long::parseLong).toArray();
        List<String> names = Arrays.stream(ids_l).mapToObj(tmp_id -> {
            SysUser workers = sysUserMapper.selectById(tmp_id);
            return workers == null ? "该用户已被删除" : workers.getName();
        }).collect(Collectors.toList());
        vo.setWorkerNames(names);
        workTicketDTOVO.setWorkTicketVO(vo);

        // 风险点分析
        workTicketDTOVO.setRiskList(workTicketTemplateService.riskList(workTicket.getContent()));

        // 审批表内容
        workTicketDTOVO.setUnsafeWorkApproveVO(unsafeWorkApproveService.getById(id).getUnsafeWorkApproveVOList());

        return workTicketDTOVO;
    }

    /**
     * 返回作业票列表
     *
     * @param workTicketQO
     * @return 作业票列表
     */
    public IPage<WorkTicketVO> getListByQO(WorkTicketQO workTicketQO) {
        Page<WorkTicketVO> page = new Page<>(workTicketQO.getCurrent(), workTicketQO.getSize());
        OrderItem orderItem = new OrderItem();
        // 排序
        orderItem.setColumn("create_time").setAsc(false);
        page.getOrders().add(orderItem);

        // 列表查询
        IPage<WorkTicketVO> res = workTicketMapper.getListByQO(page, workTicketQO);
        // 联表查询，根据id返回作业票类型
        res.getRecords().forEach(
                vo -> {
                    Long ticketType = vo.getTicketType();
                    WorkTicketTemplate template = workTicketTemplateMapper.selectById(ticketType);
                    vo.setWorkTemplateName(
                            template == null ? "作业票类型已删除" : template.getName()
                    );
                    SysPosition position = sysPositionMapper.selectById(vo.getPositionId());
                    vo.setLocationName(position == null ? "该位置不存在" : position.getName());
                }
        );


        return res;
    }


}
